import EventBus from '@/utils/eventBus';
import { startApp, endApp, createTest } from './template';
const ipcRenderer = window.require('electron').ipcRenderer;

class GenerCode {
    constructor() {
        this.hasInit = false;
        this.initEvent();
        this.callbacks = [];
        this.tests = []; //测试用例
    }
    initEvent() {
        EventBus.$on('start-app', (msg) => {
            this.hasInit = true;
            this.render();
            ipcRenderer.send("launch-app");
        })
        // 创建测试用例
        EventBus.$on('create-test', () => {
            this.tests.push({ className: [], code: [] });
            this.render();
        })

    }

    render() {
        let code = startApp();
        this.tests.forEach((test, index) => {
            code += createTest(test, index);
        })
        code += endApp();
        // 通知更新UI
        this.callbacks.forEach(fn => {
            fn(code, this.tests)
        })
    }
    exec(name, value) {
        EventBus.$emit(name, value);
    }
    update(fn) {
        this.callbacks.push(fn);
    }
    // ----------

    addElement(element) {
        const test = this.tests[this.tests.length - 1];

        let index = 0, ele;
        let code = '';
        // if (element.componentPath.length) {
        //     element.componentPath.forEach(path => {
        //         let c = index ? `component_${index}` : 'page';
        //         code += `let component_${++index} = await ${c}.$('${path}')
        //         `
        //     })
        // }
        // let hasParams = test.className.find(item => item == element.className)
        // if (!hasParams) {
        ele = index ? `component_${index}` : 'page'
        code += `    let ${element.className} = await ${ele}.$('.${element.className}');
        `
        test.className.push(element.className);
        // }
        let params = element.params ? `'${element.params}'` : '' // 附加参数处理
        //event执行
        code += `${element.className}.${element.event}(${params}) 
        `
        console.log(code)
        test.code.push(code);
        this.render();
    }

    execTest(element) {
        ipcRenderer.send("exec-event", element);
    }

    execValidate(element) {
        ipcRenderer.send("validate", element);
    }


}

export default GenerCode;